<template>
  <view class="transaction-page">
    <!-- 自定义导航栏 -->
    <custom-navbar title="记一笔" :show-back="true"></custom-navbar>
    
    <!-- 分段器：支出/收入 -->
    <view class="segment-container">
      <view 
        class="segment-item" 
        :class="{ active: activeTab === 'expense' }" 
        @click="switchTab('expense')"
      >
        支出
      </view>
      <view 
        class="segment-item" 
        :class="{ active: activeTab === 'income' }" 
        @click="switchTab('income')"
      >
        收入
      </view>
    </view>
    
    <!-- 分类选择区域 -->
    <swiper class="category-swiper" :current="swiperCurrent" @change="onSwiperChange">
      <!-- 支出分类 -->
      <swiper-item>
        <scroll-view scroll-y class="category-scroll">
          <view class="category-list">
            <view 
              v-for="(item, index) in expenseCategories" 
              :key="item.id" 
              class="category-item"
              :class="{ active: selectedCategory.id === item.id }"
              @click="selectCategory(item)"
            >
              <view class="category-icon">
                <image :src="item.icon || '/static/images/default-category.png'" mode="aspectFit"></image>
              </view>
              <text class="category-name">{{ item.name }}</text>
            </view>
          </view>
        </scroll-view>
      </swiper-item>
      
      <!-- 收入分类 -->
      <swiper-item>
        <scroll-view scroll-y class="category-scroll">
          <view class="category-list">
            <view 
              v-for="(item, index) in incomeCategories" 
              :key="item.id" 
              class="category-item"
              :class="{ active: selectedCategory.id === item.id }"
              @click="selectCategory(item)"
            >
              <view class="category-icon">
                <image :src="item.icon || '/static/images/default-category.png'" mode="aspectFit"></image>
              </view>
              <text class="category-name">{{ item.name }}</text>
            </view>
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>
    
    <!-- 键盘顶部区域 -->
    <view class="keyboard-header">
      <!-- 平台选择 -->
      <view class="platform-selector" @click="showPlatformSelector">
        <image :src="selectedPlatform.icon || '/static/images/default-platform.png'" mode="aspectFit"></image>
      </view>
      
      <!-- 输入信息区域 -->
      <view class="input-area">
        <!-- 备注输入 -->
        <view class="remark-input">
          <input type="text" v-model="formData.remark" placeholder="添加备注..." />
        </view>
        
        <!-- 金额显示和图片上传 -->
        <view class="amount-upload">
          <view class="amount-display">{{ displayAmount }}</view>
          <view class="upload-btn">
            <image src="/static/images/upload.png" mode="aspectFit"></image>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 自定义键盘 -->
    <view class="custom-keyboard">
      <!-- 数字键盘区域 -->
      <view class="number-keys">
        <view class="key-row">
          <view class="key" @click="inputKey('7')">7</view>
          <view class="key" @click="inputKey('8')">8</view>
          <view class="key" @click="inputKey('9')">9</view>
        </view>
        <view class="key-row">
          <view class="key" @click="inputKey('4')">4</view>
          <view class="key" @click="inputKey('5')">5</view>
          <view class="key" @click="inputKey('6')">6</view>
        </view>
        <view class="key-row">
          <view class="key" @click="inputKey('1')">1</view>
          <view class="key" @click="inputKey('2')">2</view>
          <view class="key" @click="inputKey('3')">3</view>
        </view>
        <view class="key-row">
          <view class="key" @click="inputKey('.')">.</view>
          <view class="key" @click="inputKey('0')">0</view>
          <view class="key delete-key" @click="deleteKey">
            <uni-icons type="close" size="24" color="#333"></uni-icons>
          </view>
        </view>
      </view>
      
      <!-- 功能键区域 -->
      <view class="function-keys">
        <view class="key date-key" @click="showDatePicker">
          <text>{{ formatDate(formData.transactionDate) }}</text>
        </view>
        <view class="key operator-key" @click="inputKey('+')">+</view>
        <view class="key operator-key" @click="inputKey('-')">-</view>
        <view class="key submit-key" @click="submitTransaction">完成</view>
      </view>
    </view>
    
    <!-- 平台选择弹窗 -->
    <uni-popup ref="platformPopup" type="bottom">
      <view class="popup-content">
        <view class="popup-header">
          <text>选择平台</text>
          <view class="close-btn" @click="closePlatformPopup">
            <uni-icons type="close" size="20" color="#999"></uni-icons>
          </view>
        </view>
        <scroll-view scroll-y class="platform-scroll">
          <view class="platform-list">
            <view 
              v-for="(item, index) in platforms" 
              :key="item.id" 
              class="platform-item"
              :class="{ active: selectedPlatform.id === item.id }"
              @click="selectPlatform(item)"
            >
              <view class="platform-icon">
                <image :src="item.icon || '/static/images/default-platform.png'" mode="aspectFit"></image>
              </view>
              <text class="platform-name">{{ item.name }}</text>
            </view>
          </view>
        </scroll-view>
      </view>
    </uni-popup>
    
    <!-- 日期选择器 -->
    <uni-datetime-picker 
      ref="datePicker"
      type="date" 
      :value="formData.transactionDate" 
      @confirm="onDateConfirm"
    ></uni-datetime-picker>
  </view>
</template>

<script>
import { queryCategories } from '@/api/category.js';
import { queryPlatforms } from '@/api/platform.js';
import { addTransaction, updateTransaction } from '@/api/transaction.js';
import CustomNavbar from '@/components/custom-navbar/custom-navbar.vue';

export default {
  components: {
    CustomNavbar
  },
  data() {
    return {
      // 当前激活的标签页：支出/收入
      activeTab: 'expense',
      swiperCurrent: 0,
      
      // 分类数据
      expenseCategories: [],
      incomeCategories: [],
      
      // 平台数据
      platforms: [],
      
      // 表单数据
      formData: {
        categoryId: null,
        platformId: null,
        amount: '',
        transactionDate: new Date(),
        remark: '',
        // 支出为0，收入为1
        type: 0
      },
      
      // 选中的分类和平台
      selectedCategory: {},
      selectedPlatform: {},
      
      // 计算器相关
      inputStack: [],
      operator: '',
      isNewInput: true,
      
      // 编辑模式
      isEdit: false,
      transactionId: null
    };
  },
  computed: {
    // 显示金额
    displayAmount() {
      if (this.formData.amount === '') {
        return '0.00';
      }
      
      // 显示计算表达式
      if (this.operator && !this.isNewInput) {
        return `${this.inputStack[0]} ${this.operator} ${this.formData.amount || ''}`;
      }
      
      return this.formData.amount;
    }
  },
  onLoad(options) {
    // 判断是否为编辑模式
    if (options.id) {
      this.isEdit = true;
      this.transactionId = options.id;
      // 加载交易详情
      this.loadTransactionDetail(options.id);
    }
    
    // 加载分类和平台数据
    this.loadCategories();
    this.loadPlatforms();
  },
  methods: {
    // 加载分类数据
    async loadCategories() {
      try {
        const res = await queryCategories({});
        if (res.data && (res.data.code === 1 || res.data.code === 200)) {
          const categories = res.data.data.records || [];
          // 分离支出和收入分类
          this.expenseCategories = categories.filter(item => item.spend === 0);
          this.incomeCategories = categories.filter(item => item.spend === 1);
        }
      } catch (error) {
        console.error('加载分类失败:', error);
        uni.showToast({
          title: '加载分类失败',
          icon: 'none'
        });
      }
    },
    
    // 加载平台数据
    async loadPlatforms() {
      try {
        const res = await queryPlatforms({});
        if (res.data && (res.data.code === 1 || res.data.code === 200)) {
          this.platforms = res.data.data.records || [];
        }
      } catch (error) {
        console.error('加载平台失败:', error);
        uni.showToast({
          title: '加载平台失败',
          icon: 'none'
        });
      }
    },
    
    // 切换标签页
    switchTab(tab) {
      this.activeTab = tab;
      this.swiperCurrent = tab === 'expense' ? 0 : 1;
      this.formData.type = tab === 'expense' ? 0 : 1;
      this.selectedCategory = {};
      this.formData.categoryId = null;
    },
    
    // 滑动切换回调
    onSwiperChange(e) {
      const current = e.detail.current;
      this.swiperCurrent = current;
      this.activeTab = current === 0 ? 'expense' : 'income';
      this.formData.type = current === 0 ? 0 : 1;
      this.selectedCategory = {};
      this.formData.categoryId = null;
    },
    
    // 选择分类
    selectCategory(category) {
      this.selectedCategory = category;
      this.formData.categoryId = category.id;
    },
    
    // 显示平台选择器
    showPlatformSelector() {
      this.$refs.platformPopup.open();
    },
    
    // 关闭平台选择器
    closePlatformPopup() {
      this.$refs.platformPopup.close();
    },
    
    // 选择平台
    selectPlatform(platform) {
      this.selectedPlatform = platform;
      this.formData.platformId = platform.id;
      this.closePlatformPopup();
    },
    
    // 显示日期选择器
    showDatePicker() {
      this.$refs.datePicker.open();
    },
    
    // 日期选择确认
    onDateConfirm(date) {
      this.formData.transactionDate = date;
    },
    
    // 格式化日期显示
    formatDate(date) {
      if (!date) return '今天';
      
      const today = new Date();
      const inputDate = new Date(date);
      
      // 判断是否为今天
      if (
        today.getFullYear() === inputDate.getFullYear() &&
        today.getMonth() === inputDate.getMonth() &&
        today.getDate() === inputDate.getDate()
      ) {
        return '今天';
      }
      
      // 格式化为 MM.DD
      const month = (inputDate.getMonth() + 1).toString().padStart(2, '0');
      const day = inputDate.getDate().toString().padStart(2, '0');
      return `${month}.${day}`;
    },
    
    // 处理键盘输入
    inputKey(key) {
      // 处理数字和小数点
      if (key === '.' || /^\d$/.test(key)) {
        if (this.isNewInput) {
          // 新输入，清空当前值
          this.formData.amount = key === '.' ? '0.' : key;
          this.isNewInput = false;
        } else {
          // 继续输入
          // 小数点只能输入一次
          if (key === '.' && this.formData.amount.includes('.')) {
            return;
          }
          
          // 限制小数点后两位
          if (this.formData.amount.includes('.')) {
            const parts = this.formData.amount.split('.');
            if (parts[1] && parts[1].length >= 2 && key !== '.') {
              return;
            }
          }
          
          this.formData.amount += key;
        }
      }
      // 处理运算符
      else if (key === '+' || key === '-') {
        // 如果已经有运算符，先计算结果
        if (this.operator) {
          this.calculate();
        }
        
        // 设置新的运算符
        this.operator = key;
        this.inputStack[0] = parseFloat(this.formData.amount) || 0;
        this.isNewInput = true;
      }
    },
    
    // 删除键
    deleteKey() {
      if (this.formData.amount.length > 0) {
        this.formData.amount = this.formData.amount.slice(0, -1);
        // 如果删除完了，显示0
        if (this.formData.amount === '') {
          this.formData.amount = '';
        }
      }
    },
    
    // 计算结果
    calculate() {
      if (!this.operator || this.isNewInput) return;
      
      const num1 = this.inputStack[0] || 0;
      const num2 = parseFloat(this.formData.amount) || 0;
      
      let result = 0;
      switch (this.operator) {
        case '+':
          result = num1 + num2;
          break;
        case '-':
          result = num1 - num2;
          break;
      }
      
      // 保留两位小数
      this.formData.amount = result.toFixed(2).replace(/\.00$/, '');
      this.operator = '';
      this.inputStack = [];
    },
    
    // 提交交易记录
    async submitTransaction() {
      // 先计算最终结果
      if (this.operator) {
        this.calculate();
      }
      
      // 验证表单
      if (!this.formData.categoryId) {
        uni.showToast({
          title: '请选择分类',
          icon: 'none'
        });
        return;
      }
      
      if (!this.formData.amount || parseFloat(this.formData.amount) <= 0) {
        uni.showToast({
          title: '请输入有效金额',
          icon: 'none'
        });
        return;
      }
      
      try {
        uni.showLoading({
          title: this.isEdit ? '更新中...' : '添加中...',
          mask: true
        });
        
        const transactionData = {
          ...this.formData,
          amount: parseFloat(this.formData.amount)
        };
        
        // 编辑模式需要添加ID
        if (this.isEdit) {
          transactionData.id = this.transactionId;
          await updateTransaction(transactionData);
        } else {
          await addTransaction(transactionData);
        }
        
        uni.showToast({
          title: this.isEdit ? '更新成功' : '添加成功',
          icon: 'success'
        });
        
        // 返回上一页
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } catch (error) {
        console.error(this.isEdit ? '更新交易失败:' : '添加交易失败:', error);
        uni.showToast({
          title: this.isEdit ? '更新失败' : '添加失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    
    // 加载交易详情（编辑模式）
    async loadTransactionDetail(id) {
      try {
        // 这里需要实现获取交易详情的接口
        // 由于API中没有提供，这里先留空
        // 实际应用中需要添加一个获取交易详情的API
        
        // const res = await getTransactionDetail(id);
        // if (res.data && (res.data.code === 1 || res.data.code === 200)) {
        //   const detail = res.data.data;
        //   this.formData = {
        //     categoryId: detail.categoryId,
        //     platformId: detail.platformId,
        //     amount: detail.amount.toString(),
        //     transactionDate: new Date(detail.transactionDate),
        //     remark: detail.remark,
        //     type: detail.type || 0
        //   };
        //   
        //   // 设置选中的分类和平台
        //   this.selectedCategory = { id: detail.categoryId };
        //   this.selectedPlatform = { id: detail.platformId };
        //   
        //   // 设置当前标签页
        //   this.activeTab = detail.type === 0 ? 'expense' : 'income';
        //   this.swiperCurrent = detail.type === 0 ? 0 : 1;
        // }
      } catch (error) {
        console.error('加载交易详情失败:', error);
        uni.showToast({
          title: '加载交易详情失败',
          icon: 'none'
        });
      }
    }
  }
};
</script>

<style lang="scss">
.transaction-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f8f8f8;
}

/* 分段器样式 */
.segment-container {
  display: flex;
  padding: 20rpx 100rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
  
  .segment-item {
    flex: 1;
    text-align: center;
    padding: 15rpx 0;
    font-size: 32rpx;
    color: #999;
    position: relative;
    
    &.active {
      color: #ff6b6b;
      font-weight: 500;
      
      &::after {
        content: '';
        position: absolute;
        bottom: -5rpx;
        left: 50%;
        transform: translateX(-50%);
        width: 60rpx;
        height: 6rpx;
        background-color: #ff6b6b;
        border-radius: 3rpx;
      }
    }
  }
}

/* 分类选择区域 */
.category-swiper {
  height: 240rpx;
  background-color: #ffffff;
  
  .category-scroll {
    height: 100%;
    white-space: nowrap;
    padding: 20rpx 0;
  }
  
  .category-list {
    display: flex;
    padding: 0 20rpx;
    flex-wrap: nowrap;
  }
  
  .category-item {
    display: inline-flex;
    flex-direction: column;
    align-items: center;
    width: 120rpx;
    margin: 0 10rpx;
    
    &.active {
      .category-icon {
        border: 2rpx solid #ff6b6b;
        background-color: rgba(255, 107, 107, 0.1);
      }
      
      .category-name {
        color: #ff6b6b;
      }
    }
    
    .category-icon {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      background-color: #f5f5f5;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 10rpx;
      border: 2rpx solid transparent;
      
      image {
        width: 50rpx;
        height: 50rpx;
      }
    }
    
    .category-name {
      font-size: 24rpx;
      color: #666;
      text-align: center;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 100%;
    }
  }
}

/* 键盘顶部区域 */
.keyboard-header {
  display: flex;
  padding: 20rpx;
  background-color: #ffffff;
  border-top: 1rpx solid #f0f0f0;
  border-bottom: 1rpx solid #f0f0f0;
  
  .platform-selector {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    background-color: #f5f5f5;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 20rpx;
    
    image {
      width: 50rpx;
      height: 50rpx;
    }
  }
  
  .input-area {
    flex: 1;
    display: flex;
    flex-direction: column;
    
    .remark-input {
      flex: 3;
      border-bottom: 1rpx solid #f0f0f0;
      padding-bottom: 10rpx;
      
      input {
        height: 100%;
        font-size: 28rpx;
      }
    }
    
    .amount-upload {
      flex: 2;
      display: flex;
      align-items: center;
      padding-top: 10rpx;
      
      .amount-display {
        flex: 4;
        font-size: 32rpx;
        font-weight: 500;
      }
      
      .upload-btn {
        flex: 1;
        display: flex;
        justify-content: flex-end;
        
        image {
          width: 40rpx;
          height: 40rpx;
        }
      }
    }
  }
}

/* 自定义键盘 */
.custom-keyboard {
  flex: 1;
  display: flex;
  background-color: #f8f8f8;
  
  .number-keys {
    flex: 3;
    display: flex;
    flex-direction: column;
    
    .key-row {
      flex: 1;
      display: flex;
    }
  }
  
  .function-keys {
    flex: 1;
    display: flex;
    flex-direction: column;
  }
  
  .key {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #ffffff;
    margin: 1rpx;
    font-size: 36rpx;
    font-weight: 500;
    
    &:active {
      background-color: #f0f0f0;
    }
    
    &.date-key {
      font-size: 28rpx;
      color: #666;
    }
    
    &.operator-key {
      color: #ff6b6b;
    }
    
    &.submit-key {
      background-color: #ff6b6b;
      color: #ffffff;
      
      &:active {
        background-color: darken(#ff6b6b, 10%);
      }
    }
  }
}

/* 平台选择弹窗 */
.popup-content {
  background-color: #ffffff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  padding-bottom: 30rpx;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    text {
      font-size: 32rpx;
      font-weight: 500;
    }
    
    .close-btn {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  
  .platform-scroll {
    max-height: 600rpx;
    padding: 20rpx 0;
  }
  
  .platform-list {
    display: flex;
    flex-wrap: wrap;
    padding: 0 20rpx;
  }
  
  .platform-item {
    width: 20%;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 30rpx;
    
    &.active {
      .platform-icon {
        border: 2rpx solid #ff6b6b;
        background-color: rgba(255, 107, 107, 0.1);
      }
      
      .platform-name {
        color: #ff6b6b;
      }
    }
    
    .platform-icon {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      background-color: #f5f5f5;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 10rpx;
      border: 2rpx solid transparent;
      
      image {
        width: 50rpx;
        height: 50rpx;
      }
    }
    
    .platform-name {
      font-size: 24rpx;
      color: #666;
      text-align: center;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 100%;
    }
  }
}
</style> 